var qiniu = require('qiniu'),
    Q = require('q');



qiniu.conf.ACCESS_KEY = 'ONSK_8uahti1XuL-C2K-I_HrnFraOIckxNnx8bM0';
qiniu.conf.SECRET_KEY = 't3_NmRTNIMIx5uIIwfZNKMJEUP1kzou7YnzxYg-S'; 
var bucketname = 'sflib';


function getUptoken() {
  var putPolicy = new qiniu.rs.PutPolicy(bucketname);
  //putPolicy.callbackUrl = callbackUrl;
  //putPolicy.callbackBody = callbackBody;
  //putPolicy.returnUrl = returnUrl;
  //putPolicy.returnBody = returnBody;
  //putPolicy.asyncOps = asyncOps;
  //putPolicy.expires = expires;

  return putPolicy.token();
}


function _upload(localFile, key, callback) {
  var extra = new qiniu.io.PutExtra();
  //extra.params = params;
  //extra.mimeType = mimeType;
  //extra.crc32 = crc32;
  //extra.checkCrc = checkCrc;

  qiniu.io.putFile(getUptoken(), key, localFile, extra, callback);
}

exports.upload = function (localFile, key){
  var deferred = Q.defer();
  _upload(localFile, key, function(err, ret) {

    if(!err) {
      // 上传成功， 处理返回值
      console.log(ret.key, ret.hash);
      deferred.resolve(ret);
    } else {
      // 上传失败， 处理返回代码
      console.log(err);
      deferred.reject(err);
      // http://developer.qiniu.com/docs/v6/api/reference/codes.html
    }
  });

  return deferred.promise;

};


